package com.zzty.servlet;

import com.zzty.common.ReadFile;
import com.zzty.common.ReadFileNames;
import com.zzty.common.Split;
import com.zzty.dao.SelfExamDao;
import com.zzty.daoimpl.SelfExamDaoImpl;
import com.zzty.entity.*;
import com.zzty.service.ComService;
import com.zzty.service.SelfExamService;
import com.zzty.serviceimpl.ComServiceImpl;
import com.zzty.serviceimpl.SelfExamServiceImpl;
import org.codehaus.jackson.map.MapperConfig;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(name = "SelfExamServlet", urlPatterns = "/SelfExamServlet")
public class SelfExamServlet extends HttpServlet {
    // String name=(String)request.getSession().getAttribute("name");  //获取前台session；
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if ("checkHomework".equals(method)) {
            checkHomework(request, response);
        }
        if ("checkLogin".equals(method)) {
            checkLogin(request, response);
        }
        if ("checkCommit".equals(method)) {
            checkCommit(request, response);
        }
        if ("startExam".equals(method)) {
            startExam(request, response);
        }
        if ("secondStartExam".equals(method)) {
            secondStartExam(request, response);
        }
        if ("getTable".equals(method)) {
            this.getTable(request, response);
        }
        if ("getStudentsWorkByDate".equals(method)) {
            this.getStudentsWorkByDate(request, response);
        }
        if ("getQuestionByDate".equals(method)) {
            this.getQuestionByDate(request, response);
        }
        if ("getContentByTransactionId".equals(method)) {
            this.getContentByTransactionId(request, response);
        }
        if ("setGrade".equals(method)) {
            this.setGrade(request, response);
        }
        if ("setWinner".equals(method)) {
            this.setWinner(request, response);
        }
    }

    protected void checkHomework(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nowDate = request.getParameter("nowDate");
        System.out.println("nowDate is: " + nowDate);
        SelfExamService selfExamService = new SelfExamServiceImpl();
        User user=(User)request.getSession().getAttribute("user");
        Integer clazzId=user.getClassId();

        Integer selfExamId = selfExamService.getSelfExamIdDate(nowDate,clazzId);
        String questionId = selfExamService.getQuestionByDate(nowDate);
        SelfExam selfExam = new SelfExam();
        selfExam.setId(selfExamId);
        selfExam.setQuestionId(questionId);

        String json = null;
        ObjectMapper mapper = new ObjectMapper();
        json = mapper.writeValueAsString(selfExam);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();

    }

    protected void checkLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        Integer userId = user.getId();
        System.out.println("servlet userId is " + userId);
        Integer selfExamId = Integer.valueOf(request.getParameter("selfExamId"));
        System.out.println("selfExamId is" + selfExamId);
        SelfExamService selfExamService = new SelfExamServiceImpl();
        Boolean flag = selfExamService.checkLogin(selfExamId, userId);
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        json = mapper.writeValueAsString(flag);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();

    }

    protected void checkCommit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        Integer userId = user.getId();
        System.out.println("servlet userId is " + userId);
        Integer selfExamId = Integer.valueOf(request.getParameter("selfExamId"));
        System.out.println("selfExamId is" + selfExamId);
        SelfExamService selfExamService = new SelfExamServiceImpl();
        Boolean flag = selfExamService.checkCommit(selfExamId, userId);
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        json = mapper.writeValueAsString(flag);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();

    }


    protected void startExam(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        Integer userId = user.getId();
        Date d=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date=sdf.format(d);
        String questionId = request.getParameter("questionId");
        Integer selfExamId = Integer.valueOf(request.getParameter("selfExamId"));
        System.out.println("selfExamId is " + selfExamId);

        SelfExamService selfExamService=new SelfExamServiceImpl();
        selfExamService.addStartTransaction(selfExamId,userId,date);

        String json = null;
        Split split = new Split();
        List<Integer> questionIdList = null;
        String content = "";
        questionIdList = split.getSplit(questionId);
        System.out.println("questionIdList :" + questionIdList.toString());
        for (int i = 0; i < questionIdList.size(); i++) {
            SelfExamDao selfExamDao = new SelfExamDaoImpl();
            Question question = new Question();
            question.setContent(i+1 + ":    " + selfExamDao.getQuestionById(questionIdList.get(i))+"\n");
            content += question.getContent();
        }
        System.out.println("content is : " + content);
        ObjectMapper mapper = new ObjectMapper();
        json = mapper.writeValueAsString(content);
        PrintWriter out = response.getWriter();
        System.out.println("json is:" + json);
        out.write(json);
        out.flush();
        out.close();


    }
    protected void secondStartExam(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String questionId = request.getParameter("questionId");

        String json = null;
        Split split = new Split();
        List<Integer> questionIdList = null;
        String content = "";
        questionIdList = split.getSplit(questionId);
        System.out.println("questionIdList :" + questionIdList.toString());
        for (int i = 0; i < questionIdList.size(); i++) {
            SelfExamDao selfExamDao = new SelfExamDaoImpl();
            Question question = new Question();
            question.setContent(selfExamDao.getQuestionById(questionIdList.get(i))+"\n");
            content += question.getContent();
        }
        System.out.println("content is : " + content);
        ObjectMapper mapper = new ObjectMapper();
        json = mapper.writeValueAsString(content);
        PrintWriter out = response.getWriter();
        System.out.println("json is:" + json);
        out.write(json);
        out.flush();
        out.close();


    }
    protected void setWinner(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer transactionId=Integer.valueOf(request.getParameter("transactionId"));
        String date = request.getParameter("date");
        SelfExamService selfExamService=new SelfExamServiceImpl();
        Integer winnerId=selfExamService.getUserIdFromTransaction(transactionId);
        Boolean flag=selfExamService.setWinner(date,winnerId);
        String json=null;
        ObjectMapper mapper = new ObjectMapper();
        json = mapper.writeValueAsString(flag);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }


        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if ("searchSelfQuestion".equals(method)) {
            searchSelfQuestion(request, response);
        }

    }

    protected void searchSelfQuestion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SelfExamService start = new SelfExamServiceImpl();
        List<SelfQuestion> questions = null;
        String json = null;
        ObjectMapper mapper = new ObjectMapper();
        if (start.historyQuestion() != null) {
            questions = start.historyQuestion();
            json = mapper.writeValueAsString(questions);
        }
        PrintWriter out = response.getWriter();

        out.write(json);
        out.flush();
        out.close();
    }

    protected void getTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        SelfExamService ses = new SelfExamServiceImpl();
        List<SelfExam> slefExams = null;
        String json = null;
        ObjectMapper mapper = new ObjectMapper();
        if (ses.getSelfExamToTable() != null) {
            slefExams = ses.getSelfExamToTable();
            json = mapper.writeValueAsString(slefExams);
        }
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }

    protected void getStudentsWorkByDate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String date = request.getParameter("date");
        SelfExamService selfExamService = new SelfExamServiceImpl();
        List<SelfStudentHomework> studentHomeworkLIst = selfExamService.getContentByDate(date);

        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        if (studentHomeworkLIst == null) {
            json = mapper.writeValueAsString("今日没有作业！");
        } else {
            json = mapper.writeValueAsString(studentHomeworkLIst);
        }

        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();

    }

    protected void getQuestionByDate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String date = request.getParameter("date");
        SelfExamService selfExamService = new SelfExamServiceImpl();
        String questionIds = selfExamService.getQuestionByDate(date);
        System.out.println("questionIds :" + questionIds);
        String json = null;
        if (questionIds == null) {
            ObjectMapper mapper = new ObjectMapper();
            json = mapper.writeValueAsString(questionIds);
            PrintWriter out = response.getWriter();
            System.out.println("json is:" + json);
            out.write(json);
            out.flush();
            out.close();
        } else {

            Split split = new Split();
            List<Integer> questionIdList = null;
            String content = "";
            questionIdList = split.getSplit(questionIds);
            System.out.println("questionIdList :" + questionIdList.toString());
            for (int i = 0; i < questionIdList.size(); i++) {
                SelfExamDao selfExamDao = new SelfExamDaoImpl();
                Question question = new Question();
                question.setContent(selfExamDao.getQuestionById(questionIdList.get(i)));
                content += question.getContent() + ";   ";
            }
            System.out.println("content is : " + content);

            ObjectMapper mapper = new ObjectMapper();
            json = mapper.writeValueAsString(content);
            PrintWriter out = response.getWriter();
            out.write(json);
            out.flush();
            out.close();
        }
    }

    protected void getContentByTransactionId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer transactionId = Integer.valueOf(request.getParameter("transactionId"));
        System.out.println("transactionId is :" + transactionId);
        SelfExamDao selfExamDao = new SelfExamDaoImpl();
        String url = selfExamDao.getUrlById(transactionId);
        System.out.println("url is :" + url);

        ReadFileNames readFileNames = new ReadFileNames();
        ReadFile readFile = new ReadFile();
        List<FileMessage> fileMessages = new ArrayList<FileMessage>();
        List<String> fileNames = readFileNames.readfile(url);
        for (String s : fileNames) {
            FileMessage fileMessage = new FileMessage();
            StringBuilder workContent = new StringBuilder("");
            workContent.append(readFile.readJava(url + "/" + s));
            fileMessage.setFileName(s);
            fileMessage.setWorkContent(workContent);
            fileMessages.add(fileMessage);
        }
//        String content = null;
//        for (int i = 0; i < fileMessages.size(); i++) {
//            content += fileMessages.get(i).getFileName().toString() + fileMessages.get(i).getWorkContent().toString();
//        }
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(fileMessages);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();

    }

    protected void setGrade(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer grade = Integer.valueOf(request.getParameter("score"));
        Integer transactionId = Integer.valueOf(request.getParameter("transactionId"));
        System.out.println("transactionId :"+transactionId+"score :"+grade);
        SelfExamService selfExamService = new SelfExamServiceImpl();
        selfExamService.setGrade(transactionId, grade);

    }


    public static void main(String args[]) throws IOException {
        SelfExamService selfExamService = new SelfExamServiceImpl();
        Boolean aa = selfExamService.checkCommit(29,44);

        SelfExamDao selfExamDao=new SelfExamDaoImpl();
        Boolean bb=selfExamDao.checkCommit(29,44);
        System.out.println("测试：" + aa+bb);

    }
}
